package com.koron.css2.baseConfig.impl;

import com.google.common.collect.Maps;
import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.bean.PhraseFieldBean;
import com.koron.css2.baseConfig.mapper.MsgPhraseMapper;
import com.koron.css2.baseConfig.queryBean.PhraseFieldQueryBean;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.util.Constant;
import com.koron.util.JsonUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 短信模板字段查询
 *
 * @author 杨嘉慧
 * @date 2021/11/15
 */
public class PhraseFieldQuery implements ServerInterface {
    private static Logger logger = LogManager.getLogger(PhraseFieldQuery.class);

    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        @SuppressWarnings("rawtypes")
        MessageBean<Map> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", Map.class);
        try {
            PhraseFieldQueryBean bean = JsonUtils.objectToPojo(req.getData(), PhraseFieldQueryBean.class);
            MsgPhraseMapper mapper = factory.getMapper(MsgPhraseMapper.class);
            List<PhraseFieldBean> phraseFieldList = mapper.phraseFieldQuery(bean.getPhraseNo());
            phraseFieldList.stream().forEach(phraseField->phraseField.setMergeStr(phraseField.getFieldName()+":"+phraseField.getField()));
            Map<String,List<PhraseFieldBean>> phraseFieldMap = phraseFieldList.stream().collect(Collectors.groupingBy(PhraseFieldBean::getPhraseNo));
            Map<String,List<String>> resultMap = Maps.newHashMap();
            phraseFieldMap.forEach((k,v)->resultMap.put(k,v.stream().map(phraseField->phraseField.getFieldName()+":"+phraseField.getField()).collect(Collectors.toList())));
            info.setCode(Constant.MESSAGE_INT_SUCCESS);
            info.setData(resultMap);
        } catch (Exception e) {
            info.setCode(Constant.MESSAGE_INT_FAIL);
            info.setDescription("查询失败");
            logger.error("短信模板字段查询失败", e);
        }
        return info;
    }
}
